package com.example.blue;

import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.blue.ui.DynamicWaveFormView;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;

public class XiangxiaActivity extends AppCompatActivity implements DataProcessorManager.DataUpdateListener,DataProcessorManagerRight.DataUpdateListener{
    private static final String TAG = "PingjuActivity";
    private String deviceId;
    private BluetoothService bluetoothService;
    private boolean isBound=false;
    private Button btn;
    private Integer handDir;
    private ImageView imageView;
    private TextView shuomingText;
    private ProgressDialog progressDialog;
    private Boolean startFlag=false;
    private DynamicWaveFormView waveformViewX1;
    private DynamicWaveFormView waveformViewY1;
    private DynamicWaveFormView waveformViewZ1;
    private DynamicWaveFormView waveformViewX2;
    private DynamicWaveFormView waveformViewY2;
    private DynamicWaveFormView waveformViewZ2;
    private LinearLayout groupLayout;
    private DataProcessorManager processorManager;
//    private ConcurrentLinkedQueue<byte[]> dataQueue = new ConcurrentLinkedQueue<>();
//    private ConcurrentLinkedQueue<byte[]> dataQueue2 = new ConcurrentLinkedQueue<>();
private LinkedBlockingDeque<byte[]> dataQueue = new LinkedBlockingDeque<>();
    private LinkedBlockingDeque<byte[]> dataQueue2 = new LinkedBlockingDeque<>();
    private Integer conDeviceNum=1;
    private String deviceMacLeft;
    private String deviceMacRight;
    private Boolean isJiaozhun1=false;
    private Boolean isJiaozhun2=false;
    private LinearLayout groupSpinner;
    private Spinner spinner;
    private Integer selectedSensorNum=0;
    private DataProcessorManagerRight processorManagerRight;
    private Boolean isLeftDeviceReceived=false;
    private Boolean isRightDeviceReceived=false;

    private final ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
            bluetoothService = binder.getService();
            isBound = true;
            Log.d("ServiceTest", "onServiceConnected: bound=" + isBound);
            if(conDeviceNum==1){
                if(handDir==1) {
                    dataQueue  = bluetoothService.getDataQueueLeft();
                    processorManager = DataProcessorManager.getInstance(dataQueue);
                }else{
                    dataQueue2  = bluetoothService.getDataQueueRight();
                    processorManager = DataProcessorManager.getInstance(dataQueue2);
                }
            }
            else{
                dataQueue  = bluetoothService.getDataQueueLeft();
                dataQueue2  = bluetoothService.getDataQueueRight();
                processorManager = DataProcessorManager.getInstance(dataQueue);
                processorManagerRight=DataProcessorManagerRight.getInstance(dataQueue2);
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CrashHandler.getInstance().init(this);
        setContentView(R.layout.activity_xiangxia);
        // 开启返回箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(null);
        getSupportActionBar().setTitle("双手置于胸前手心向下测试");
        btn = findViewById(R.id.startBtn);
        SharedPreferences sp = getSharedPreferences("my_cache", Context.MODE_PRIVATE);
        conDeviceNum = sp.getInt("conDeviceNum", 1);
        isLeftDeviceReceived=sp.getBoolean("isLeftDeviceReceived",false);
        isRightDeviceReceived=sp.getBoolean("isRightDeviceReceived",false);
        if(conDeviceNum==1) {

            handDir = sp.getInt("handDirection",0);
            if(handDir==1){
                if(isLeftDeviceReceived==false){
                    Toast.makeText(XiangxiaActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                }

                deviceId = sp.getString("DEVICE_ADDRESS_LEFT", "");
            }else{
                if(isRightDeviceReceived==false){
                    Toast.makeText(XiangxiaActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                }
                deviceId = sp.getString("DEVICE_ADDRESS_RIGHT", "");
            }
//            if (deviceId == "" || deviceId.isEmpty()) {
//                Toast.makeText(XiangxiaActivity.this, "未获取到蓝牙MAC地址，请重新连接", Toast.LENGTH_SHORT).show();
//            }

        }
        if(conDeviceNum==2){
            if(isLeftDeviceReceived==false){
                Toast.makeText(XiangxiaActivity.this, "左手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
            }else if(isRightDeviceReceived==false){
                Toast.makeText(XiangxiaActivity.this, "右手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
            }
            deviceMacLeft = sp.getString("DEVICE_ADDRESS_LEFT","");
            deviceMacRight=sp.getString("DEVICE_ADDRESS_RIGHT","");
            System.out.println("magcor----deviceMacLeft:"+deviceMacLeft);
            System.out.println("magcor----deviceMacRight:"+deviceMacRight);
//            if (deviceMacLeft == null || deviceMacLeft.isEmpty() || deviceMacRight == null || deviceMacRight.isEmpty()) {
//                Toast.makeText(XiangxiaActivity.this, "未获取到蓝牙MAC地址，请重新连接", Toast.LENGTH_SHORT).show();
//            }

        }
        imageView=findViewById(R.id.imageView);
        shuomingText=findViewById(R.id.shuoming);
        groupLayout=findViewById(R.id.group_container);
        groupSpinner=findViewById(R.id.group_spinner);

        waveformViewX1 = findViewById(R.id.waveformView1);
        waveformViewY1 = findViewById(R.id.waveformView2);
        waveformViewZ1 = findViewById(R.id.waveformView3);
        waveformViewX2 = findViewById(R.id.waveformView4);
        waveformViewY2 = findViewById(R.id.waveformView5);
        waveformViewZ2 = findViewById(R.id.waveformView6);
        waveformViewX1.setYtitle("加速度模值(传感器1)");
        waveformViewX1.setYRange(-20,20);
        waveformViewY1.setYtitle("加速度模值(传感器2)");
        waveformViewY1.setYRange(-20,20);
        waveformViewZ1.setYtitle("加速度模值(传感器3)");
        waveformViewZ1.setYRange(-20,20);
        waveformViewX2.setYtitle("加速度模值(传感器4)");
        waveformViewX2.setYRange(-20,20);
        waveformViewY2.setYtitle("加速度模值(传感器5)");
        waveformViewY2.setYRange(-20,20);
        waveformViewZ2.setYtitle("加速度模值(传感器6)");
        waveformViewZ2.setYRange(-20,20);
        if(startFlag==false){
            groupLayout.setVisibility(View.GONE);
        }else{
            groupLayout.setVisibility(View.VISIBLE);
        }
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    if (conDeviceNum == 1) {
                        if (handDir == 1) {
                            if (isLeftDeviceReceived == false) {
                                Toast.makeText(XiangxiaActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                                return;
                            }
                        }
                        if (handDir == 2) {
                            if (isRightDeviceReceived == false) {
                                Toast.makeText(XiangxiaActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                                return;
                            }
                        }
                        groupLayout.setVisibility(View.VISIBLE);
                        imageView.setVisibility(View.GONE);
                        shuomingText.setVisibility(View.GONE);
                        btn.setVisibility(View.GONE);
                        groupSpinner.setVisibility(View.GONE);
                        processorManager.setDeviceMac(deviceId.replace(":", ""));
                        processorManager.temp = handDir;
                        processorManager.setDataUpdateListener(XiangxiaActivity.this);
                        processorManager.startProcessing();
                        processorManager.setProcessingFunction(ProcessingFunction.Blank);
                        processorManager.setzero();
                        processorManager.setProcessingFunction(ProcessingFunction.WingBeating);
                        Toast.makeText(XiangxiaActivity.this, "开始测试", Toast.LENGTH_SHORT).show();

                    } else {
                        if (isLeftDeviceReceived == false) {
                            Toast.makeText(XiangxiaActivity.this, "左手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                        } else if (isRightDeviceReceived == false) {
                            Toast.makeText(XiangxiaActivity.this, "右手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                        } else {
                            groupLayout.setVisibility(View.VISIBLE);
                            imageView.setVisibility(View.GONE);
                            shuomingText.setVisibility(View.GONE);
                            btn.setVisibility(View.GONE);
                            groupSpinner.setVisibility(View.VISIBLE);
                            processorManager.setDataUpdateListener(XiangxiaActivity.this);
                            processorManager.startProcessing();
                            processorManager.setDeviceMac(deviceMacLeft.replace(":", ""));
                            processorManager.temp = 1;
                            processorManager.setProcessingFunction(ProcessingFunction.Blank);
                            processorManager.setzero();
                            processorManager.setProcessingFunction(ProcessingFunction.WingBeating);

                            processorManagerRight.setDataUpdateListener(XiangxiaActivity.this);
                            processorManagerRight.startProcessing();
                            processorManagerRight.setDeviceMac(deviceMacRight.replace(":", ""));
                            processorManagerRight.temp = 2;
                            processorManagerRight.setProcessingFunction(ProcessingFunction.Blank);
                            processorManagerRight.setzero();
                            processorManagerRight.setProcessingFunction(ProcessingFunction.WingBeating);

                            Toast.makeText(XiangxiaActivity.this, "开始测试", Toast.LENGTH_SHORT).show();
                        }
                    }

            }
        });

        spinner = findViewById(R.id.modeSpinner);
        String[] options = {"左手", "右手"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_item,
                options
        );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
// 监听选择
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selected = options[position];
                if(position!=selectedSensorNum){
                    waveformViewX1.clearDataPoints();
                    waveformViewY1.clearDataPoints();
                    waveformViewZ1.clearDataPoints();
                    waveformViewX2.clearDataPoints();
                    waveformViewY2.clearDataPoints();
                    waveformViewZ2.clearDataPoints();
                }
                selectedSensorNum=position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

    }
    @Override
    protected void onStart() {
        super.onStart();
        if(conDeviceNum==1) {
            if(handDir==1) {
                Intent intent = new Intent(this, BluetoothService.class);
                intent.putExtra("DEVICE_ADDRESS_LEFT", deviceId);
                bindService(intent, connection, Context.BIND_AUTO_CREATE);
            }else{
                Intent intent = new Intent(this, BluetoothService.class);
                intent.putExtra("DEVICE_ADDRESS_RIGHT", deviceId);
                bindService(intent, connection, Context.BIND_AUTO_CREATE);
            }
        }
        if(conDeviceNum==2) {
            Intent intent = new Intent(this, BluetoothService.class);
            intent.putExtra("DEVICE_ADDRESS_LEFT", deviceMacLeft);
            intent.putExtra("DEVICE_ADDRESS_RIGHT", deviceMacRight); // 如果需要
            bindService(intent, connection, Context.BIND_AUTO_CREATE);
        }


    }
    @Override
    public void onDataProcessed(ProcessedData data) {
        String flag = data.getFlag();
        System.out.println("pingju-Flag:"+flag);
        if(flag.equals("fileNull")){
            Toast.makeText(this,"缺少文件",Toast.LENGTH_SHORT).show();
            return;
        }
        if(flag.equals("allout")) {
            String processedValue = data.getAcccle();
            System.out.println("zhenchan-Hex: " + processedValue);
            String[] dataArr = processedValue.split(" ");   // 按逗号分割
//            String da1x = dataArr[1].length()>10?dataArr[1].substring(0,8):dataArr[1];
//            String da1y = dataArr[2].length()>10?dataArr[2].substring(0,8):dataArr[2];
//            String da1z = dataArr[3].length()>10?dataArr[3].substring(0,8):dataArr[3];
//
//            String da2x = dataArr[5].length()>10?dataArr[5].substring(0,8):dataArr[5];
//            String da2y = dataArr[6].length()>10?dataArr[6].substring(0,8):dataArr[6];
//            String da2z = dataArr[7].length()>10?dataArr[7].substring(0,8):dataArr[7];
//
//            String da3x = dataArr[9].length()>10?dataArr[9].substring(0,8):dataArr[9];
//            String da3y = dataArr[10].length()>10?dataArr[10].substring(0,8):dataArr[10];
//            String da3z = dataArr[11].length()>10?dataArr[11].substring(0,8):dataArr[11];
//
//
//            String da4x = dataArr[13].length()>10?dataArr[13].substring(0,8):dataArr[13];
//            String da4y = dataArr[14].length()>10?dataArr[14].substring(0,8):dataArr[14];
//            String da4z = dataArr[15].length()>10?dataArr[15].substring(0,8):dataArr[15];
//
//            String da5x = dataArr[17].length()>10?dataArr[17].substring(0,8):dataArr[17];
//            String da5y = dataArr[18].length()>10?dataArr[18].substring(0,8):dataArr[18];
//            String da5z = dataArr[19].length()>10?dataArr[19].substring(0,8):dataArr[19];
//
//            String da6x = dataArr[21].length()>10?dataArr[21].substring(0,8):dataArr[21];
//            String da6y = dataArr[22].length()>10?dataArr[22].substring(0,8):dataArr[22];
//            String da6z = dataArr[23].length()>10?dataArr[23].substring(0,8):dataArr[23];
//
//            double g=9.7936;
//            double magnitude = Math.sqrt(Float.parseFloat(da1x) * Float.parseFloat(da1x) + Float.parseFloat(da1y) * Float.parseFloat(da1y) + Float.parseFloat(da1z) * Float.parseFloat(da1z))-g;
//            double magnitude2 = Math.sqrt(Float.parseFloat(da2x) * Float.parseFloat(da2x) + Float.parseFloat(da2y) * Float.parseFloat(da2y) + Float.parseFloat(da2z) * Float.parseFloat(da2z))-g;
//            double magnitude3 = Math.sqrt(Float.parseFloat(da3x) * Float.parseFloat(da3x) + Float.parseFloat(da3y) * Float.parseFloat(da3y) + Float.parseFloat(da3z) * Float.parseFloat(da3z))-g;
//            double magnitude4 = Math.sqrt(Float.parseFloat(da4x) * Float.parseFloat(da4x) + Float.parseFloat(da4y) * Float.parseFloat(da4y) + Float.parseFloat(da4z) * Float.parseFloat(da4z))-g;
//            double magnitude5 = Math.sqrt(Float.parseFloat(da5x) * Float.parseFloat(da5x) + Float.parseFloat(da5y) * Float.parseFloat(da5y) + Float.parseFloat(da5z) * Float.parseFloat(da5z))-g;
//            double magnitude6 = Math.sqrt(Float.parseFloat(da6x) * Float.parseFloat(da6x) + Float.parseFloat(da6y) * Float.parseFloat(da6y) + Float.parseFloat(da6z) * Float.parseFloat(da6z))-g;
            if(selectedSensorNum==0) {
                waveformViewX1.addDataPoint(Float.parseFloat(dataArr[0]));
                waveformViewY1.addDataPoint(Float.parseFloat(dataArr[1]));
                waveformViewZ1.addDataPoint(Float.parseFloat(dataArr[2]));
                waveformViewX2.addDataPoint(Float.parseFloat(dataArr[3]));
                waveformViewY2.addDataPoint(Float.parseFloat(dataArr[4]));
                waveformViewZ2.addDataPoint(Float.parseFloat(dataArr[5]));
            }


        }
        if(flag.equals("success")){
            isJiaozhun1=true;
            processorManager.stopProcessing();
            SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean("isXiangxia", true);
            editor.apply();
            if(conDeviceNum==1) {
                Toast.makeText(XiangxiaActivity.this,"测试完成",Toast.LENGTH_SHORT).show();
                finish();
            }
            if(conDeviceNum==2){
                if (isJiaozhun1==true && isJiaozhun2==true) {
                    Toast.makeText(XiangxiaActivity.this,"测试完成",Toast.LENGTH_SHORT).show();
                    finish();
                }
            }

        }
    }

    @Override
    public void onDataProcessedRight(ProcessedData data) {

        String flag = data.getFlag();
        System.out.println("zhenchan-Flag:"+flag);
        if(flag.equals("fileNull")){
            Toast.makeText(this,"缺少文件",Toast.LENGTH_SHORT).show();
            return;
        }
        if(flag.equals("allout")) {
            String processedValue = data.getAcccle();
            System.out.println("zhenchan-Hex: " + processedValue);
            String[] dataArr = processedValue.split(" ");   // 按逗号分割
//            String da1x = dataArr[1].length() > 10 ? dataArr[1].substring(0, 8) : dataArr[1];
//            String da1y = dataArr[2].length() > 10 ? dataArr[2].substring(0, 8) : dataArr[2];
//            String da1z = dataArr[3].length() > 10 ? dataArr[3].substring(0, 8) : dataArr[3];
//
//            String da2x = dataArr[5].length() > 10 ? dataArr[5].substring(0, 8) : dataArr[5];
//            String da2y = dataArr[6].length() > 10 ? dataArr[6].substring(0, 8) : dataArr[6];
//            String da2z = dataArr[7].length() > 10 ? dataArr[7].substring(0, 8) : dataArr[7];
//
//            String da3x = dataArr[9].length() > 10 ? dataArr[9].substring(0, 8) : dataArr[9];
//            String da3y = dataArr[10].length() > 10 ? dataArr[10].substring(0, 8) : dataArr[10];
//            String da3z = dataArr[11].length() > 10 ? dataArr[11].substring(0, 8) : dataArr[11];
//
//
//            String da4x = dataArr[13].length() > 10 ? dataArr[13].substring(0, 8) : dataArr[13];
//            String da4y = dataArr[14].length() > 10 ? dataArr[14].substring(0, 8) : dataArr[14];
//            String da4z = dataArr[15].length() > 10 ? dataArr[15].substring(0, 8) : dataArr[15];
//
//            String da5x = dataArr[17].length() > 10 ? dataArr[17].substring(0, 8) : dataArr[17];
//            String da5y = dataArr[18].length() > 10 ? dataArr[18].substring(0, 8) : dataArr[18];
//            String da5z = dataArr[19].length() > 10 ? dataArr[19].substring(0, 8) : dataArr[19];
//
//            String da6x = dataArr[21].length() > 10 ? dataArr[21].substring(0, 8) : dataArr[21];
//            String da6y = dataArr[22].length() > 10 ? dataArr[22].substring(0, 8) : dataArr[22];
//            String da6z = dataArr[23].length() > 10 ? dataArr[23].substring(0, 8) : dataArr[23];
//
//            double g=9.7936;
//            double magnitude = Math.sqrt(Float.parseFloat(da1x) * Float.parseFloat(da1x) + Float.parseFloat(da1y) * Float.parseFloat(da1y) + Float.parseFloat(da1z) * Float.parseFloat(da1z))-g;
//            double magnitude2 = Math.sqrt(Float.parseFloat(da2x) * Float.parseFloat(da2x) + Float.parseFloat(da2y) * Float.parseFloat(da2y) + Float.parseFloat(da2z) * Float.parseFloat(da2z))-g;
//            double magnitude3 = Math.sqrt(Float.parseFloat(da3x) * Float.parseFloat(da3x) + Float.parseFloat(da3y) * Float.parseFloat(da3y) + Float.parseFloat(da3z) * Float.parseFloat(da3z))-g;
//            double magnitude4 = Math.sqrt(Float.parseFloat(da4x) * Float.parseFloat(da4x) + Float.parseFloat(da4y) * Float.parseFloat(da4y) + Float.parseFloat(da4z) * Float.parseFloat(da4z))-g;
//            double magnitude5 = Math.sqrt(Float.parseFloat(da5x) * Float.parseFloat(da5x) + Float.parseFloat(da5y) * Float.parseFloat(da5y) + Float.parseFloat(da5z) * Float.parseFloat(da5z))-g;
//            double magnitude6 = Math.sqrt(Float.parseFloat(da6x) * Float.parseFloat(da6x) + Float.parseFloat(da6y) * Float.parseFloat(da6y) + Float.parseFloat(da6z) * Float.parseFloat(da6z))-g;
            if (selectedSensorNum == 1){
                waveformViewX1.addDataPoint(Float.parseFloat(dataArr[0]));
                waveformViewY1.addDataPoint(Float.parseFloat(dataArr[1]));
                waveformViewZ1.addDataPoint(Float.parseFloat(dataArr[2]));
                waveformViewX2.addDataPoint(Float.parseFloat(dataArr[3]));
                waveformViewY2.addDataPoint(Float.parseFloat(dataArr[4]));
                waveformViewZ2.addDataPoint(Float.parseFloat(dataArr[5]));
            }
        }
        if(flag.equals("success")){
            isJiaozhun2=true;
            processorManagerRight.stopProcessing();
            if(isJiaozhun1==true && isJiaozhun2==true) {
                Toast.makeText(XiangxiaActivity.this, "测试完成", Toast.LENGTH_SHORT).show();
                SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("isXiangxia", true);
                editor.apply();
                finish();
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish(); // 结束当前Activity，返回上一个
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(conDeviceNum==1) {
            processorManager.setProcessingFunction(ProcessingFunction.Blank);
            processorManager.setzero();
            processorManager.stopProcessing();
        }else {
            processorManager.setProcessingFunction(ProcessingFunction.Blank);
            processorManager.setzero();
            processorManager.stopProcessing();
            processorManagerRight.setProcessingFunction(ProcessingFunction.Blank);
            processorManagerRight.setzero();
            processorManagerRight.stopProcessing();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(conDeviceNum==1) {
            processorManager.setProcessingFunction(ProcessingFunction.Blank);
            processorManager.setzero();
            processorManager.stopProcessing();
        }else {
            processorManager.setProcessingFunction(ProcessingFunction.Blank);
            processorManager.setzero();
            processorManager.stopProcessing();
            processorManagerRight.setProcessingFunction(ProcessingFunction.Blank);
            processorManagerRight.setzero();
            processorManagerRight.stopProcessing();
        }
    }
}